// Copyright (C) Kumo inc. and its affiliates.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//
#pragma once

#include <pollux/expression/complex_view_types.h>
#include <pollux/functions/udf.h>

namespace kumo::pollux::functions {
    template<typename TExec, typename Compare>
    struct MapTopNImpl {
        POLLUX_DEFINE_FUNCTION_TYPES(TExec);

        using It = typename arg_type<Map<Orderable<T1>, Generic<T2> > >::Iterator;

        void call(
            out_type<Array<Orderable<T1> > > &out,
            const arg_type<Map<Orderable<T1>, Generic<T2> > > &inputMap,
            int64_t n) {
            POLLUX_USER_CHECK_GE(n, 0, "n must be greater than or equal to 0");

            if (n == 0 || inputMap.size() == 0) {
                return;
            }

            Compare comparator;
            std::priority_queue<It, std::vector<It>, Compare> topEntries(comparator);

            for (auto it = inputMap.begin(); it != inputMap.end(); ++it) {
                if (topEntries.size() < n) {
                    topEntries.push(it);
                } else if (comparator(it, topEntries.top())) {
                    topEntries.pop();
                    topEntries.push(it);
                }
            }
            std::vector<It> result;
            result.reserve(topEntries.size());
            while (!topEntries.empty()) {
                result.push_back(topEntries.top());
                topEntries.pop();
            }
            // Reverse the order of the result to be in descending order.
            for (int i = result.size() - 1; i >= 0; i--) {
                out.push_back(result[i]->first);
            }
        }
    };
} // namespace kumo::pollux::functions
